<?php
class SucculentService {
    /**
     * @var SucculentService
     */
    private static $instance;

    /**
     * Get the instance of SucculentService.
     *
     * @return SucculentService
     */
    public static function get() {
        if (!self::$instance) {
            self::$instance = new SucculentService();
        }
        return self::$instance;
    }

    public function __construct() {

    }

    /**
     * 花房的信息
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function funcInfo($userId,$reqTime){
        $status = 0;
        $funcInfo = array();
        $seed = array();
        $flowerportInfo = array();
        $flowerportPlantInfo = array();
        $isUnlock = $this->checkUnlock($userId);
        if ($isUnlock !=0){
            $status = -1;
           return  array(
               'code' => $status,
               'funcInfo' => $funcInfo
           );
        }

        //获取花房的信息
        $succulentFuncInfo = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_SUCCULENT_FUNC_INFO);
        $funcInfo = $succulentFuncInfo->toArray();

        //已解锁的多肉
        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_SEED);
        if ($seedList->getListCount() >0){
            $seed = $seedList->toArray();
        }

        //获取解锁的花盆
        $succulentFlowerportInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_FLOWERPORT_INFO);
        if ($succulentFlowerportInfoList->getListCount() >0) {
            $flowerportInfo = $succulentFlowerportInfoList->toArray();
        }

        //获取花盆的种植信息
        $plantList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_PLANT_INFO);
        if ($plantList->getListCount() >0) {
            $flowerportPlantInfo = $plantList->toArray();
        }
        return array(
            'code' => $status,
            'funcInfo' => $funcInfo,
            'seedList' => $seed,
            'flowerportInfo' => $flowerportInfo,
            'flowerportPlantInfo' => $flowerportPlantInfo
        );
    }


    /**
     * 花房升级（）
     * @param $userId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function funcUnlock($userId,$reqTime){
        $isUnlock = $this->checkUnlock($userId);
        if ($isUnlock ==0){
            return  array(
                'code' => 201,//201代表花房已解锁
            );
        }

        //解锁花房
        $userLevel =  UserService::get()->getUserLevel($userId);
        $succulentFuncInfo = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_SUCCULENT_FUNC_INFO);
        if (!$succulentFuncInfo){
            $succulentFuncInfo = new SucculentFuncInfoVo($userId,0,0,$reqTime,true);
        }
        $succulentFuncInfo->setLevel($userLevel);
        $succulentFuncInfo->setStatus(1);
        $succulentFuncInfo->setCreateTime($reqTime);
        SzPersister::get()->setVo($succulentFuncInfo);

        //获取默认花盆的外观
        $appearanceId = 1;
        $appearanceResult = $this->flowerportAppearanceGet($userId,$appearanceId,$reqTime);
        if ($appearanceResult != 0){
            return  array(
                'code' => 202,//202获取免费的花盆外观失败
            );
        }

        //获取送的默认多肉花卡
        $succulentFree = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'succulentFree', true)['value']);
        foreach ($succulentFree as $itemId=>$count) {
            GameService::get()->handleEntity($userId, $itemId, $count, true, true);
        }

        //解锁免费的花盆（前三排）
        for ($row=1;$row<=3;$row++){
            for($num=1;$num<=3;$num++) {
               $this->flowerportUnlock($userId,$row,$num,$reqTime) ;
            }
        }
        return  array(
            'code' => 0,//解锁成功
        );
    }


    /**
     * 玩家拥有的花盆外观
     * @param $userId
     * @return array
     * @throws SzException
     */
    public  function  flowerportAppearanceInfo($userId){
        /**
         * @var SucculentFlowerportAppearanceInfoVoList $succulentFlowerportAppearanceInfoList
         * @var SucculentFlowerportAppearanceInfoVo $succulentFlowerportAppearanceInfo
         */
        //获取玩家已拥有的花盆外观
        $succulentFlowerportAppearanceInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_FLOWERPORT_APPEARANCE_INFO);
        $succulentFlowerportAppearanceInfoData = $succulentFlowerportAppearanceInfoList->toArray();

        return $succulentFlowerportAppearanceInfoData;

    }

    /**
     * 获取多肉花盆外观
     * @param $userId
     * @param $appearanceId
     * @param $reqTime
     * @return int
     * @throws SzException
     */

    public function flowerportAppearanceGet($userId,$appearanceId,$reqTime){
        $flowerportAppearanceConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_VASE_APPEARANCE, $appearanceId, true);
        if (!$flowerportAppearanceConf) {
            $result = -1;
            return  $result;
        }

        $vaseId = $flowerportAppearanceConf['vaseId'];
        $costItem = $flowerportAppearanceConf['price'];
        if ($costItem) {
            //获取花棚外观的消耗
            $input = '';
            foreach ($costItem as $entityId => $count) {
                GameService::get()->handleEntity($userId, $entityId, $count, true, true);
                $input .= $entityId . ':' . abs($count) . '|';
            }
        }

        /**
         * @var SucculentFlowerportAppearanceInfoVoList $succulentFlowerportAppearanceInfoList
         * @var SucculentFlowerportAppearanceInfoVo $succulentFlowerportAppearanceInfo
         */
        $succulentFlowerportAppearanceInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_FLOWERPORT_APPEARANCE_INFO);
        $succulentFlowerportAppearanceInfo = $succulentFlowerportAppearanceInfoList->getElement($appearanceId,false);
        if (!$succulentFlowerportAppearanceInfo) {
            $succulentFlowerportAppearanceInfo = new SucculentFlowerportAppearanceInfoVo($userId,$appearanceId,$vaseId,$reqTime,true);
            $succulentFlowerportAppearanceInfoList->addElement($succulentFlowerportAppearanceInfo);
            $succulentFlowerportAppearanceInfoList->setElement($appearanceId,$succulentFlowerportAppearanceInfo);
        }else {
            $succulentFlowerportAppearanceInfo->setAppearanceId($appearanceId);
            $succulentFlowerportAppearanceInfo->setVaseId($vaseId);
            $succulentFlowerportAppearanceInfo->setCreateTime($reqTime);
            $succulentFlowerportAppearanceInfoList->updateElement($appearanceId,$succulentFlowerportAppearanceInfo);
        }

        SzPersister::get()->setVoList($succulentFlowerportAppearanceInfoList);

        $result = 0;
        return $result;
    }



    /**
     * 多肉花盆外观替换 如果没有则会先购买
     * @param $userId
     * @param $appearanceId
     * @param $pos
     * @param $reqTime
     * @return bool
     * @throws SzException
     */
    public function flowerportAppearanceReplace($userId,$appearanceId,$pos,$reqTime){

        $flowerportAppearanceConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_VASE_APPEARANCE, $appearanceId, true);
        $vaseId = $flowerportAppearanceConf['vaseId'];
        /**
         * @var SucculentFlowerportAppearanceInfoVoList $succulentFlowerportAppearanceInfoList
         * @var SucculentFlowerportAppearanceInfoVo $succulentFlowerportAppearanceInfo
         */
        $succulentFlowerportAppearanceInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_FLOWERPORT_APPEARANCE_INFO);
        $succulentFlowerportAppearanceInfo = $succulentFlowerportAppearanceInfoList->getElement($appearanceId,false);
        if (!$succulentFlowerportAppearanceInfo){
            $this->flowerportAppearanceGet($userId,$appearanceId,$reqTime);
        }

        //替换花盆的外观
        /**
         * @var SucculentFlowerportInfoVoList $succulentFlowerportInfoList
         * @var SucculentFlowerportInfoVo $succulentFlowerportInfo
         */
        $succulentFlowerportInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_FLOWERPORT_INFO);
        foreach ($pos as $position){
            $succulentFlowerportInfo = $succulentFlowerportInfoList->getElement($position,false);
            if (!$succulentFlowerportInfo){
               continue;
            }
            $succulentFlowerportInfo->setAppearanceId($appearanceId);
            $succulentFlowerportInfo->setVaseId($vaseId);
            $succulentFlowerportInfo->setUpdateTime($reqTime);
            $succulentFlowerportInfoList->updateElement($position,$succulentFlowerportInfo);
        }

        SzPersister::get()->setVoList($succulentFlowerportInfoList);

        return true;

    }

    /**
     * 多肉花盆解锁
     * @param $userId
     * @param $row
     * @param $num
     * @param $reqTime
     * @return int
     * @throws SzException
     */
    public function flowerportUnlock($userId,$row,$num,$reqTime){
        $flowerportConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_VASE_UNLOCK, $row, true);
        if (!$flowerportConf) {
            $result = -1;//配置不存在
            return  $result;
        }

        $userLevel =  UserService::get()->getUserLevel($userId);

        if ($flowerportConf['level'] > $userLevel){
            $result = 1;//玩家等级不够
            return  $result;
        }

        $costItem = $flowerportConf['price'];
        if ($costItem) {
            //解锁花棚的消耗
            $input = '';
            foreach ($costItem as $entityId => $count) {
                GameService::get()->handleEntity($userId, $entityId, $count, true, true);
                $input .= $entityId . ':' . abs($count) . '|';
            }
        }

        $flowerportLevel = 1;//暂时写死；

        /**
         * @var SucculentFlowerportInfoVoList $succulentFlowerportInfoList
         * @var SucculentFlowerportInfoVo $succulentFlowerportInfo
         */
        $succulentFlowerportInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_FLOWERPORT_INFO);
        $succulentFlowerportInfo = $succulentFlowerportInfoList->getElement($row.'-'.$num,false);
        if (!$succulentFlowerportInfo) {
            $succulentFlowerportInfo = new SucculentFlowerportInfoVo($userId,$row.'-'.$num,$flowerportLevel,1,57011000,$reqTime,0,true);
            $succulentFlowerportInfoList->addElement($succulentFlowerportInfo);
            $succulentFlowerportInfoList->setElement($row.'-'.$num,$succulentFlowerportInfo);
        }else {
            $succulentFlowerportInfo->setAppearanceId(1);
            $succulentFlowerportInfo->setVaseId(57011000);
            $succulentFlowerportInfo->setUpdateTime($reqTime);
            $succulentFlowerportInfoList->updateElement($row.'-'.$num,$succulentFlowerportInfo);
        }

        SzPersister::get()->setVoList($succulentFlowerportInfoList);

        $result = 0;
        return $result;
    }


    /**
     * 培育/变色
     * @param $landId
     * @param $userId
     * @param $flowerId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function cultivate($userId,$landId,$flowerId,$reqTime) {
        /**
         * @var NewCultivateLandVoList $userLandList
         * @var NewCultivateLandVo $userLand
         * @var ModuleItemVoList $itemList
         */
        $flowerInfo = SzConfig::get()->loadAppConfig(GameConst::CONFIG_SEED_CONDITION, $flowerId, true);
        $profile = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        if ($profile->getLevel() < $flowerInfo['unlockLv']) {
            throw new SzException(29002); // 用户等级不够
        }

        $userLandList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_NEW_CULTIVATE_LAND);
        $userLand = $userLandList->getElement($landId);
        if ($userLand->getFlowerId()) {
            throw new SzException(29007, $landId); // 已种植/变色
        }
        if ($flowerInfo['unlockType'] == 4) {
            $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
            $item = $itemList->getElementsByItemDefId($flowerInfo['taskId']);
            if (is_null($item)) {
                throw new SzException(29002);
            }
        }

        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_SEED);
        $seedVo = $seedList->getElement($flowerId, false);
        if ($seedVo) {
            throw new SzException(29008, $flowerId); // 已解锁
        }

        NewCultivateService::get()->clearCultivateHarvestTime($userId,$reqTime);

        // 扣除道具
        $inputTid = '';
        foreach ($flowerInfo['itemId'][0] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $inputTid .= $entityId . ':' . abs($count) . '|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(99999996,$userId,0,$inputTid,'plant');//消耗资源上报

        // 成功率
        $rand = mt_rand(1,100);
        if ($rand <= $flowerInfo['successRate']) {
            $harvestTime = $reqTime + $flowerInfo['waitingTime'];
            $userLand->setFlowerId($flowerId);
            $userLand->setHarvestTime($harvestTime);
            $userLand->setUnlock_res(1);
            $userLandList->updateElement($landId, $userLand);
            SzPersister::get()->setVoList($userLandList);
            $unlockRes = 1;
            $str = '&success';
        } else {
            $unlockRes = 0;
            $str = '&fail';
        }

        // 数据采集:鲜花培育/变色
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:flower|action:cultivate|',
                'item' => $flowerId,
                'value' => 1
            )
        ));

        // 数据采集:鲜花培育/变色消耗
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
            'clientData' => array(
                'tid' => $inputTid,
                'item' => 'flower_cultivate&' . $flowerId
            )
        ));

        // 数据采集:鲜花培育/变色结果
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cultivate|action:result|',
                'item' => $flowerId.$str,
                'value' => 1
            )
        ));

        return array('landList'=>$userLand->toArray(),'unlockRes'=>$unlockRes,'flowerId'=>$flowerId);
    }

    /**
     * 培育收获
     * @param $userId
     * @param $landId
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function cultivateHarvest($userId,$landId,$reqTime) {
        NewCultivateService::get()->refreshCultivateHarvestTime($userId,$reqTime);
        /**
         * @var NewCultivateLandVoList $userLandList
         * @var NewCultivateLandVo $userLand
         */
        $userLandList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_NEW_CULTIVATE_LAND);
        $userLand = $userLandList->getElement($landId);

        $harvestTime = $userLand->getHarvestTime();
        $flowerId = $userLand->getFlowerId();

        if ($harvestTime > $reqTime) {
            throw new SzException(20255, array($flowerId, $reqTime, $harvestTime));
        }

        // 解锁
        $seedList = $this->unlockSeed($userId, $flowerId);
        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
        $redisDb->hSet(GameConst::CACHE_KEY_NEW_CULTIVATE_WATCH.$userId,$flowerId,$reqTime);
        NewTaskService::get()->setProgress($userId,GameConst::TASK_CULTIVATE,count($seedList->toArray()));
        TreeService::get()->setProgress($userId,GameConst::TREE_TASK_CULTIVATE_FLOWER,count($seedList->toArray()));

        $userLand->setUnlock_res(0);
        $userLand->setHarvestTime(0);
        $userLand->setFlowerId(0);
        $userLand->setVideoTime(0);
        $userLandList->updateElement($landId, $userLand);
        SzPersister::get()->setVoList($userLandList);

        $cropSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $flowerId, true);
        $amount = 1;
        list($itemList) = ItemService::get()->processItems($userId, [$cropSetting['exp'] => $amount]);
        SzPersister::get()->setVoList($itemList);
        $outTid = $cropSetting['exp'].':'.$amount.'|';

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $outTid,
                'item' => 'cultivate&'.$flowerId,
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:cultivate|action:receive|',
                'item' => $flowerId,
                'value' => 1
            )
        ));

        // 数据采集
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_UPGRADE, array(
            'clientData' => array(
                'tid' => 'objective:cultivate_unlock|item:'.$flowerId.'|',
                'item' => 'fromlevel:|changelev:unlock|targetlev:|',
                'value' => 1
            )
        ));

        // 种子等级排行榜
        $isUp = SeedService::get()->setFlowerLevel($userId,GameService::get()->getReqTime(),true);

        //社团竞赛任务进度添加
        UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_4, $reqTime,1);

        return $seedList->toArray();
    }

    /**
     * 解锁种子
     * @param int $userId
     * @param int $seedId
     * @return PlantSeedVoList
     */
    public function unlockSeed($userId, $seedId)
    {
        // 解锁
        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_SEED);
        $seedVo = $seedList->getElement($seedId, false);
        if ($seedVo) {
            return $seedList;
        }
        $seedVo = new SucculentSeedVo($userId, $seedId, 0, 0, true);
        $seedList->addElement($seedVo);
        $seedList->setElement($seedId, $seedVo);
        SzPersister::get()->setVoList($seedList);

        $seedSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_SEED_CONDITION, $seedId, true);
        if ($seedSetting['taskId'] != -1) {
            MissionService::get()->remove($userId, $seedSetting['taskId'], false);
        }

        // 种子等级排行榜
        SeedService::get()->setFlowerLevel($userId,GameService::get()->getReqTime());

        // 数据采集:花卉手册解锁鲜花
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:book|action:unlock|',
                'item' => $seedId,
                'value' => 1
            )
        ));

        // 数据采集:鲜花解锁
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_UPGRADE, array(
            'clientData' => array(
                'tid' => 'objective:book|item:' . $seedId . '|',
                'item' => 'fromlevel:|changelev:unlock|targetlev:|',
                'value' => 1
            )
        ));
        // 更新任务进度---解锁X朵花
        MissionService::get()->progress($userId, GameConst::ENTITY_ACTION_UNLOCK_SEED, GameConst::ENTITY_TYPE_NULL, $seedId, 1);
        return $seedList;
    }


    /**
     * 种子升级
     * @param $userId
     * @param $seedId
     * @return array|PlantSeedVo|SzAbstractVo
     * @throws SzException
     */
    public function seedUpgrade($userId, $seedId)
    {
        $cropSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $seedId, true);
        /**
         * @var PlantSeedVo $seedVo
         */
        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_SEED);
        $seedVo = $seedList->getElement($seedId);
        $level = $seedVo->getLevel();
        if (!isset($cropSetting['upgrade'][$level]) || !isset($cropSetting['coin'][$level])) {
            return $seedVo;
        }
        $count = $cropSetting['upgrade'][$level];
        $price = $cropSetting['coin'][$level];

        $tid = '';

        $videoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_VIDEO);
        $video = $videoList->getElement($seedId, false);
        if (false && $cropSetting['freeVideoLevel'] == $level && !$video) {
            $video = new VideoVo($userId, $seedId, 1, GameService::get()->getReqTime());
            $videoList->addElement($video);
            $videoList->setElement($seedId, $video);
        } else {
            /**
             * @var ModuleItemVoList $itemList
             * @var ModuleItemVo $item
             */
            $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);

            //扣除道具
            list($itemList) = ItemService::get()->processItems($userId, [$cropSetting['exp'] => -$count], $itemList);

            $seedEntityId = EntityService::get()->buildEntityId(GameConst::ENTITY_ACTION_GET, GameConst::ENTITY_TYPE_ITEM, $cropSetting['exp']);
            $tid = $seedEntityId.':'.$count.'|';


            // 扣除买家金币，增加买家物品放入仓库
            GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_TOKEN, $price, true);
            $tid .= GameConst::ENTITY_ACTION_CONSUME_TOKEN.':'.$price.'|';

            SzPersister::get()->setVoList($itemList);
        }


        $level++;
        $seedVo->setLevel($level);
        $seedList->updateElement($seedId, $seedVo);

        SzPersister::get()->setVoList($seedList);
        SzPersister::get()->setVoList($videoList);
        // 数据采集: 鲜花升级
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:book|action:upgrade|',
                'item' => $seedId,
                'value' => 1
            )
        ));

        // 数据采集: 鲜花升级
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_UPGRADE, array(
            'clientData' => array(
                'tid' => 'objective:book|item:' . $seedId . '|',
                'item' => 'fromlevel:' . ($level - 1) . '|changelev:1|targetlev:' . $level . '|',
                'value' => 1
            )
        ));

        // 消耗
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
            'clientData' => array(
                'tid' => $tid,
                'item' => 'book_upgrade&'.$seedId,
            )
        ));

        // 种子等级排行榜
        $isUp = SeedService::get()->setFlowerLevel($userId,GameService::get()->getReqTime(),true);

        //社团竞赛任务进度添加
        UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_3, GameService::get()->getReqTime(),1);

        return array(
            'plant' => $seedVo->toArray(),
            'isUp' => $isUp
        );
    }


    /**
     * 种植/替换多肉
     *
     * @param int $userId
     * @param int $pos
     * @param int $seedId
     * @param int $reqTime
     * @throws SzException 20253,20254
     * @return PlantVo
     */
    public function plant($userId, $pos, $seedId, $reqTime)
    {

        $cropSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $seedId, true);

        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_SEED);
        $seedVo = $seedList->getElement($seedId, false);
        if (!$seedVo) {//种子未解锁
            throw new SzException(20260, array($seedId));
        }

        //判断花盆是否解锁
        /**
         * @var SucculentFlowerportInfoVoList $succulentFlowerportInfoList
         * @var SucculentFlowerportInfoVo $succulentFlowerportInfo
         */
        $succulentFlowerportInfoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_FLOWERPORT_INFO);
        $succulentFlowerportInfo = $succulentFlowerportInfoList->getElement($pos,false);
        if (!$succulentFlowerportInfo) {
            throw new SzException(20264, array($pos));
        }

        // 验证土地是否已经被种植
        $plantList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_PLANT_INFO);
        $plant = $plantList->getElement($pos, false);
        if (!$plant) {
            // 创建植株
            $plant = new SucculentPlantInfoVo($userId, $pos,$seedId,0,-1,0,$reqTime,0,true);
        }else{
            $plant->setSeedId($seedId);
            $plant->setLevel(0);
            $plant->setStatus(-1);
            $plant->setHarvestTime(0);
            $plant->setUpdateTime(0);
        }

        /**
         * @var PlantSeedVo $seedVo
         */

        if ($plant->isInsert() && !SzUtility::checkArrayKey($pos, $plantList->getList())) {
            $plantList->setElement($pos, $plant);
            $plantList->addElement($plant);
        } else {
            $plantList->updateElement($pos, $plant);
        }

        SzPersister::get()->setVoList($plantList);

        //更新任务进度
        MissionService::get()->progress($userId, GameConst::ENTITY_ACTION_PLANT_PUT, GameConst::ENTITY_TYPE_ITEM, $seedId, 1);
        TreeService::get()->updateProgress($userId,GameConst::TREE_TASK_PLANT_FLOWER,1);
        NewTaskService::get()->updateDailyTask($userId,GameConst::DAILY_TASK_PLANT,1);
        TrainingService::get()->updateProgress($userId,GameConst::TRAINING_TASK_PLANT_FLOWER,1);

        return $plant;
    }


    /**
     * 浇水多肉
     * @param $userId
     * @param $position
     * @param $reqTime
     * @return mixed
     * @throws SzException
     */
    public function water($userId, $position, $reqTime)
    {
        $plantList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_PLANT_INFO);
        $plant = $plantList->getElement($position, false);

        if ($plant->getSeedId() == -1) {
            throw new SzException(20261, array($position));
        }

        if ($plant->getStatus() != -1) {
            throw new SzException(20262, array($position));
        }

        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_SEED);
        $seedVo = $seedList->getElement($plant->getSeedId(), false);
        $level = $seedVo->getLevel();//获取种子的等级

        // 更新状态与时间
        $plant->setStatus(0);
        $plant->setHarvestTime($reqTime);
        $plant->setLevel($level);
        $plant->setUpdateTime($reqTime);
        $plantList->updateElement($position, $plant);
        SzPersister::get()->setVoList($plantList);

        $cropSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $plant->getSeedId(), true);
        $tid = '';
        foreach ($cropSetting['consumption'] as $entityId => $count) {
            GameService::get()->handleEntity($userId, $entityId, $count, true);
            $tid .= "{$entityId}:{$count}|";
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_PLANT_PLANT,$userId,0,$tid,'water');//消耗资源上报

        return $plant->toArray();
    }



    /**
     * 收获多肉
     * @param $userId
     * @param $position
     * @param $reqTime
     * @param $plantList
     * @param $hasBuffFlower
     * @param $hasBuffSeed
     * @return array
     * @throws SzException
     */
    public function harvest($userId, $position, $reqTime,$plantList,$hasBuffFlower,$hasBuffSeed)
    {

        $plant = $plantList->getElement($position);
        $seedId = $plant->getSeedId();
        if ($seedId== -1) {
            return array();
//            throw new SzException(20258, array($decorId, -1));
        }
        $status = $plant->getStatus();
        //未浇水不能收获
        if ($status == -1) {
            return array();
//            throw new SzException(20263, array($decorId));
        }

        $harvestTime = $plant->getHarvestTime();
        // 验证植株是否成熟
        if ($reqTime < $harvestTime) {
            return array();
//            throw new SzException(20255, array($seedId, $reqTime, $harvestTime));
        }

        /**
         * @var PlantSeedVo $seedVo
         */
        $seedList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_SEED);
        $seedVo = $seedList->getElement($seedId);
        $cropSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $seedId, true);

        $maxHarvestNum = intval($cropSetting['frequency'][$seedVo->getLevel()]);//最大收获次数
        $count = intval($cropSetting['cropCount'][$seedVo->getLevel()]);//计算可收获数量
        $getTime = $cropSetting['interval'][$plant->getLevel()];
        $harvestNum = intval(($reqTime - $harvestTime) / $getTime);
        if ($harvestNum == 0) {
            $harvestNum =1;
        }

        if (($harvestNum + $status) >= $maxHarvestNum){
            $harvestNum = $maxHarvestNum - $status;
        }

        if ($hasBuffFlower){
            $count = $count + 1;
        }
        //20200409
        //获取玩家该花朵是否具有种子掉落数量加成
        $seedBuff = FlowersUpgradeService::get()->getFlowerBuff($userId,$seedId,GameConst::FLOWER_TYPE_6);
        if (!empty($seedBuff)){
            if ($seedBuff[0] == 2){
                $count = $count + $seedBuff[1];
            }
            if ($seedBuff[0] == 1){
                $count = ceil($count*(1+$seedBuff[1]/100));
            }
        }
        $items = [$seedId => $count*$harvestNum];

        // 收获种子
        $amount = $cropSetting['seedProp'][$plant->getLevel()];
        $weight = $cropSetting['seedWeight'][$plant->getLevel()];
        //20200409
        //获取玩家该花朵是否具有种子掉落概率加成
        $weightBuff = FlowersUpgradeService::get()->getFlowerBuff($userId,$seedId,GameConst::FLOWER_TYPE_4);
        if (!empty($weightBuff)){
            if ($weightBuff[0] == 2){
                $weight = $weight + $weightBuff[1];
            }
            if ($weightBuff[0] == 1){
                $weight = ceil($weight*(1+$weightBuff[1]/100));
            }
        }
        $rand = mt_rand(1,100);
        $isDrop = false;

        if ($hasBuffSeed){
            $amount = $amount + 1;
        }
        if (($harvestNum + $status) >= $maxHarvestNum) {//收获次数已经到达上限
            $plant->setStatus(-1);
            $plant->setHarvestTime(0);
            $plant->setLevel(0);
            $plant->setUpdateTime(0);
        } else {
            //20200409
            //获取玩家该花朵是否具有时间加成
            $getTime = $cropSetting['interval'][$plant->getLevel()];
            $flowerBuff = FlowersUpgradeService::get()->getFlowerBuff($userId,$seedId,GameConst::FLOWER_TYPE_5);
            if (!empty($flowerBuff)){
                if ($flowerBuff[0] == 2){
                    $getTime = $getTime - $flowerBuff[1];
                }
                if ($flowerBuff[0] == 1){
                    $getTime = ceil($getTime*(1-$flowerBuff[1]/100));
                }
            }

            //下次成熟的时间
            $nextHarvestTime = $harvestTime + ($harvestNum+1)*$getTime;

            $plant->setStatus($status+$harvestNum);
            $plant->setHarvestTime($nextHarvestTime);
            $plant->setUpdateTime($reqTime);
        }
        // 更新植株
        $plantList->updateElement($position, $plant);
        SzPersister::get()->setVoList($plantList);

        // 收获道具
        list($itemList) = ItemService::get()->processItems($userId, $items);
        SzPersister::get()->setVoList($itemList);

        $outTid = $seedId . ':' . $count . '|';

        if ($rand <= $weight) {
            //20200409
            //获取玩家该花朵是否种子数量掉落加成
            $amountBuff = FlowersUpgradeService::get()->getFlowerBuff($userId,$seedId,GameConst::FLOWER_TYPE_3);
            if (!empty($amountBuff)){
                if ($amountBuff[0] == 2){
                    $amount = $amount + $amountBuff[1];
                }
                if ($amountBuff[0] == 1){
                    $amount = ceil($amount*(1+$amountBuff[1]/100));
                }
            }
            list($itemList) = ItemService::get()->processItems($userId, [$cropSetting['exp'] => $amount*$harvestNum], $itemList);
            SzPersister::get()->setVoList($itemList);
            $outTid = $cropSetting['exp'] . ':' . $amount . '|';
            $isDrop = true;
        }

        if (isset($cropSetting['experience'])) {// 收获获得经验
            UserService::get()->updateExp($userId, $cropSetting['experience'][$seedVo->getLevel()]*$harvestNum);
            //跟新店铺经营数据（经验）
            UserShopService::get()->record($userId,2,14000001,$cropSetting['experience'][$seedVo->getLevel()]*$harvestNum);
            $outTid .= GameConst::ENTITY_ACTION_GET_EXP . ':' . $cropSetting['experience'][$seedVo->getLevel()]*$harvestNum. '|';
        }

        //更新任务进度
        MissionService::get()->progress($userId, GameConst::ENTITY_ACTION_PLANT_HARVEST, GameConst::ENTITY_TYPE_ITEM, $seedId, 1);


        TrainingService::get()->updateProgress($userId,GameConst::TRAINING_TASK_HARVEST_FLOWER,1);
        $itemNum = 0;
        //验证活动是否开启
        $activityPersonalGoalsId = ActivityService::get()->getActivityPersonalGoalsIndexId($userId,$reqTime);
        if ($activityPersonalGoalsId) {
            $upper = 0;
            //获取植株配置
            $seedSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $seedId, true);
            $needTime = $seedSetting['interval'][0];
            //获取几率掉落结果
            $dropConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_ACTIVITY_PLANT_PER_PLANT, null, true);
            if (!empty($needTime) && !empty($dropConfs)){
                //依据生长时间进行随机掉落道具数量
                foreach ($dropConfs as $key=>$data){
                    if ($needTime >= $data['rowthRange'][0] && $needTime <= $data['rowthRange'][1]){
                        $upper = $data['dropProbability'];
                        break;
                    }
                }
                if (!empty($upper)){
                    $mineNum = rand(0,100);
                    if ($mineNum <= $upper){
                        //发送给玩家活动道具
                        ActivityService::get()->updateActivityPersonalGoalsNum($userId,$activityPersonalGoalsId,1,false,true);
                        $itemNum = 1;
                    }
                }
            }
        }

        // 更新合约任务进度
        $contractData = ContractService::get()->getContractOpenAndTask($userId,GameConst::CONTRACT_TASK_5,$reqTime);
        if (!empty($contractData) && !empty($contractData['task']) && !empty($contractData['session'])){
            if ($reqTime >= $contractData['start'] && $reqTime <= $contractData['end']){
                ContractService::get()->updateTaskProgress($userId,$contractData['session'],$contractData['task']['pos'],$contractData['task']['taskId'],$reqTime);
            }
        }

        //社团竞赛任务进度添加
        UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_1, $reqTime,$count,$seedId);

        return array($seedId,$plant, $count,array($cropSetting['exp'] => $amount),$isDrop,$itemNum);
    }

    /**
     * 加速成熟(使用加速道具/看视频)
     *
     * @param int $userId
     * @param int $position
     * @param int $reqTime
     * @param int $isFree
     * @throws SzException 20206
     * @return boolean
     */
    public function speedUp($userId, $position, $reqTime,$isFree = 0)
    {

        $plantList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_SUCCULENT_PLANT_INFO);
        $plant = $plantList->getElement($position);
        $seedId = $plant->getSeedId();
        if ($seedId == -1) {
            throw new SzException(20258, array($position, $seedId));
        }
        if ($plant->getStatus() == -1) {
            throw new SzException(20263, array($position));
        }

        if ($plant->getHarvestTime() <= $reqTime) {
            throw new SzException(20265, array($position));
        }

        //使用道具加速
        if (!$isFree) {
            //消耗加速道具
            list($itemList) = ItemService::get()->processItems($userId, [GameConst::ITEM_ID_SPEED_UP_POTION => -1]);
            SzPersister::get()->setVoList($itemList);
        }

        // 直接成熟
        $plant->setHarvestTime($reqTime);
        $plantList->updateElement($position, $plant);
        SzPersister::get()->setVoList($plantList);

        // 数据采集: 农场植物速成
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:farm|action:speed|',
                'item' => $seedId,
                'value' => 1
            )
        ));


        // 数据采集: 加速消耗道具
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
            'clientData' => array(
                'tid' => GameConst::ITEM_ID_SPEED_UP_POTION . ':1|',
                'item' => 'farm_speed&' . $seedId
            )
        ));
        return true;
    }

    /**
     * 检查花房是否开启
     * @param $userId
     * @return int
     */
    private function checkUnlock($userId){
        $result = -1;

        //获取花房的信息
        $succulentFuncInfo = SzPersister::get()->getVo($userId, GameConst::ORM_NAME_SUCCULENT_FUNC_INFO);
        if ($succulentFuncInfo){
            if ($succulentFuncInfo->getStatus() ==1 ){
                $result = 0;
            }

        }

        return $result;
    }
}